package com.itheima.reggie.controller;

import com.itheima.reggie.entity.Address;
import com.itheima.reggie.entity.Result;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class AddressController {


    @Autowired
    private AddressService addressService ;

    //获取地址列表
    @GetMapping("/addressBook/list")
    @ResponseBody
    public Result list( HttpSession httpSession ){
        //获取用户的id
        Long user = (Long) httpSession.getAttribute("user");
        List<Address> addressList = addressService.List(user);
        return Result.success(addressList);
    }

    //添加地址
    @PostMapping("/addressBook")
    @ResponseBody
    public Result addAddress(@RequestBody Address address , HttpSession httpSession ){
        //获取当前用户名
        Long userId = (Long) httpSession.getAttribute("user");
        address.setUpdateUser(userId);
        address.setCreateUser(userId);
        address.setUserId(userId);
        addressService.addAddress(address);
        return Result.success(null);
    }

    //修改默认值
    @PutMapping("/addressBook/default")
    @ResponseBody
    public Result updateDefault( @RequestBody Address address , HttpSession httpSession  ){
        Long userId = (Long) httpSession.getAttribute("user");
        //修改默认值
        addressService.updateDefault( address.getId() , userId );
        return Result.success(null);
    }


    @GetMapping("/addressBook/{id}")
    @ResponseBody
    public Result findById ( @PathVariable  Long id ){
        Address address = addressService.findById (id);
        System.out.println(id);
        return Result.success(address);
    }

    @PutMapping("/addressBook")
    @ResponseBody
    public Result updateAddress( @RequestBody Address address , HttpSession httpSession ){
        //获取用户id
        Long userId = (Long) httpSession.getAttribute("user");
        //调用业务层保存数据
        addressService.updateAddress(address);
        return Result.success(null) ;
    }

    @GetMapping("/addressBook/default")
    @ResponseBody
    public Result findDefault( HttpSession httpSession  ){
        Long userId = (Long) httpSession.getAttribute("user");
        Address address = addressService.findDefatult(userId);
        return Result.success(address) ;
    }

}
